function Tabinator() {
 
  this.localtabs = [];
  this.cloudtabs = {};

  this.fillFromAct = function() {
    chrome.tabs.query(
      {},
      (function(ctx) {
        return (function(tabs) {
          for(var i=0; i<tabs.length; i++) {
            var tabid = ctx.localtabs.push(
              {
                "id":tabs[i].id,
                "title":tabs[i].title,
                "url":tabs[i].url
              }
            );
            ctx.localtabs[tabid-1].tabid = tabid-1;
          }
          ctx.displayTabFields(document.getElementById("tab_local"), ctx.localtabs);
        });
      })(this)
    );
  };

  this.fillFromSync = function() {
    chrome.storage.sync.get(
      "cloudtabs",
      (function(ctx) {
        return (function(items) {
          if(!chrome.runtime.lastError) {
            if(items.cloudtabs) {
              ctx.cloudtabs=items.cloudtabs;
              for(var key in ctx.cloudtabs) {
                for(var i=0; i<ctx.cloudtabs[key].length; i++) {
                  ctx.cloudtabs[key][i].tabid = undefined;
                }
                ctx.displayCloudItem(document.getElementById("tab_cloud"), key, ctx.cloudtabs[key]);
                var opt1 = document.createElement('option');
                var opt2 = document.createElement('option');
                opt1.value = key;
                opt1.innerHTML = key;
                opt2.value = key;
                opt2.innerHTML = key;
                document.getElementById("overwrite_tabs").appendChild(opt1);
                document.getElementById("delete_tabs").appendChild(opt2);
              }
            }
          }else{
            console.log("error: "+chrome.runtime.lastError);
          }
        });
      })(this)
    );
  };

  this.displayCloudItem = function(container,name,tabs) {
    var div = document.createElement('div');
    var title = document.createElement('label');
    var button = document.createElement('button');
    div.className = "cloud_item";
    button.innerHTML = "open all";
    title.innerHTML = name;
    title.title = "click to fold / unfold";
    button.id = div.class+"_"+name+"_button";
    title.id = div.class+"_"+name+"_title";
    div.appendChild(title);
    div.appendChild(button);
    container.appendChild(div);
    var list = this.displayTabFields(div, tabs);
    button.addEventListener(
      'click',
      (function (_tabs) {
        return (function (e) {
          for(var i=0; i<_tabs.length; i++) {
            chrome.tabs.create(
              { "url": _tabs[i].url },
              function(tab){}
            );
          }
        });
      })(tabs)
    );
    title.addEventListener(
      'click',
      (function (_list) {
        return (function (e) {
          if(_list.style.display=='none') {
            _list.style.display = 'block';
          } else {
            _list.style.display = 'none';
          }
        });
      })(list)
    );
  };

  this.displayTabFields = function(container,tabfields) {
    var list = document.createElement('ul');
    for(var i=0; i<tabfields.length; i++) {
      this._customAdd(tabfields[i], list);
    }
    container.appendChild(list);
    return list;
  };

  this._customAdd = function(tabfield,list) {
    if(tabfield) {
      var item = document.createElement('li');
      item.appendChild(document.createTextNode(tabfield.title));
      item.id = tabfield.tabid;
      item.addEventListener(
        'click',
        (function(url,tabid) {
          return (function(e) {
            if(tabid === undefined) {
              chrome.tabs.create(
                { "url": url },
                function(tab){}
              );
            } else {
              chrome.tabs.highlight(
                { "tabs": tabid },
                function(window){}
              );
            }
          });
        })(tabfield.url, tabfield.tabid)
      );
      list.appendChild(item);
    }
  };

  this.initTabsystem = function() {
    var tabclick = function(e) {
      document.getElementById("tab_action").style.display = "none";
      document.getElementById("tab_local").style.display = "none";
      document.getElementById("tab_cloud").style.display = "none";
      document.getElementById("tab_settings").style.display = "none";
      document.getElementById(e.currentTarget.dataset.toggle).style.display = "block";
    };
    document.getElementById("tab_action").style.display = "block";
    document.getElementById("tab_local").style.display = "none";
    document.getElementById("tab_cloud").style.display = "none";
    document.getElementById("tab_settings").style.display = "none";
    document.getElementById("tab_action_header").addEventListener('click', tabclick);
    document.getElementById("tab_local_header").addEventListener('click', tabclick);
    document.getElementById("tab_cloud_header").addEventListener('click', tabclick);
    document.getElementById("tab_settings_header").addEventListener('click', tabclick);
  };

  this.initSystemmenu = function() {
    document.getElementById("btn_close").addEventListener(
      'click',
      function(e) {
        window.close();
      }
    );
    document.getElementById("googlecode_link").addEventListener(
      'click',
      function(e) {
        chrome.tabs.create(
          { "url":"https://code.google.com/p/chrome-tabinator/" },
          function (tab) {}
        );
      }
    );
  };

  this.initActionmenu = function() {
    document.getElementById("btn_saveas").addEventListener(
      'click',
      (function(ctx) {
        return (function(e) {
          var tsn = document.getElementById("edit_saveas").value;
          if(tsn) {
            ctx.cloudtabs[tsn] = ctx.localtabs;
            ctx.saveCloudTabs();
          } else {
            console.log("not saved");
          }
        });
      })(this)
    );
    document.getElementById("btn_delete").addEventListener(
      'click',
      (function(ctx) {
        return (function(e) {
          var tsn = document.getElementById("delete_tabs").value;
          if(tsn) {
            delete ctx.cloudtabs[tsn];
          }
          ctx.saveCloudTabs();
        });
      })(this)
    );
  };

  this.saveCloudTabs = function() {
    chrome.storage.sync.set(
      {"cloudtabs":this.cloudtabs},
      function() {
        if(chrome.runtime.lastError) {
          console.log("error: "+chrome.runtime.lastError);
        } else {
          location.reload(true);
        }
      }
    );
  };
};


// --- Execution starts here ---
var tabinator; 
document.addEventListener('DOMContentLoaded', function () {
  tabinator = new Tabinator();
  tabinator.initTabsystem();
  tabinator.initSystemmenu();
  tabinator.initActionmenu();
  tabinator.fillFromAct();
  tabinator.fillFromSync();
});
